package com.example.homemodule.view.ui;

import static android.graphics.Typeface.BOLD;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.StyleSpan;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.examination.mlib.baseold.AnswerDetailsListEntity;
import com.example.homemodule.R;
import com.examination.mlib.baseold.ModuleBaseFragment;
import com.examination.mlib.view.TrapezoidTextView;
import com.example.homemodule.listener.OnAnswerCardListener;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.ScreenUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class AnswerCardFragment extends ModuleBaseFragment {

    public static AnswerCardFragment getInstance(int position, AnswerDetailsListEntity.DataItem answerData, int count) {
        AnswerCardFragment fragment = new AnswerCardFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putSerializable("answerData", answerData);
        bundle.putInt("count", count);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * answerNormalCl:已答题UI
     * answerCl：未答题UI
     * answerTomorrowCl：明天更精彩UI
     */
    private View answerFl, answerCl, answerTomorrowCl, answerNormalCl;
    private TextView titleNormalTv;
    //    private ImageView flagNormalIv;
    private int position;
    private OnAnswerCardListener listener;
    private AnswerDetailsListEntity.DataItem data;
    private int count;
    private TextView dateTv;
    private ImageView tomorrowIv, gotoTodayIv, preDayTomorrowIv, preDayIv, nextDayIv, chooseLeftIv, chooseRightIv, preDayNormal, nextDayNormal;
    private TextView checkHistoryTomorrowTv, titleTv, checkHistoryTv, checkHistoryNormalTv;
    private TrapezoidTextView correctRateTtv;
    private TrapezoidTextView errorRateTtv;
    private TextView errorTv, correctTv;
    private ImageView answerFlagIv;
    private TextView answerInfoTv;
    private TextView correctRealTv, errorRealTv;
    private View answerLl;
    private TextView answerTv, yourAnswerTv;

    private final int titleMaxLines = 3;

    @Override
    public int bondLayout() {
        return R.layout.fragment_answer_card;
    }

    @Override
    public void initView() {
        position = getArguments().getInt("position");
        data = (AnswerDetailsListEntity.DataItem) getArguments().getSerializable("answerData");
        count = getArguments().getInt("count");
        if (count == 0) {
            return;
        }
        answerFl = findViewById(R.id.fl_answer);
        answerCl = findViewById(R.id.cl_answer);
        answerTomorrowCl = findViewById(R.id.cl_answer_tomorrow);
        answerNormalCl = findViewById(R.id.cl_answer_normal);
        titleNormalTv = findViewById(R.id.tv_title_normal);
//        flagNormalIv = findViewById(R.id.iv_flag_normal);
        dateTv = findViewById(R.id.tv_date);
        tomorrowIv = findViewById(R.id.iv_tomorrow);
        gotoTodayIv = findViewById(R.id.iv_goto_today);
        preDayTomorrowIv = findViewById(R.id.iv_pre_day_tomorrow);
        checkHistoryTomorrowTv = findViewById(R.id.iv_check_history_tomorrow);
        checkHistoryTv = findViewById(R.id.iv_check_history);
        preDayIv = findViewById(R.id.iv_pre_day);
        nextDayIv = findViewById(R.id.iv_next_day);
        chooseLeftIv = findViewById(R.id.iv_choose_left);
        chooseRightIv = findViewById(R.id.iv_choose_right);
        titleTv = findViewById(R.id.tv_title);
        preDayNormal = findViewById(R.id.iv_pre_day_normal);
        nextDayNormal = findViewById(R.id.iv_next_day_normal);
        correctRateTtv = findViewById(R.id.ttv_correct_rate);
        errorRateTtv = findViewById(R.id.ttv_error_rate);
        errorTv = findViewById(R.id.tv_error);
        correctTv = findViewById(R.id.tv_correct);
        answerInfoTv = findViewById(R.id.tv_answer_info);
        answerFlagIv = findViewById(R.id.iv_answer_flag);
        checkHistoryNormalTv = findViewById(R.id.iv_check_history_normal);
        correctRealTv = findViewById(R.id.tv_correct_real);
        errorRealTv = findViewById(R.id.tv_error_real);
        answerLl = findViewById(R.id.ll_answer);
        answerTv = findViewById(R.id.tv_answer);
        yourAnswerTv = findViewById(R.id.tv_your_answer);


        if (position == count - 1) {
            answerCl.setVisibility(View.GONE);
            answerTomorrowCl.setVisibility(View.VISIBLE);
            answerNormalCl.setVisibility(View.GONE);
            dateTv.setText("明天更精彩");
            tomorrowIv.setVisibility(View.VISIBLE);
            gotoTodayIv.setVisibility(View.GONE);
        } else {
//            platformActivitiesId	Integer	1000
//            platformActivitiesSubjectId	Integer	43
//            subjectTitle	String	测试-第一天
//            answerOption	Boolean	false
//            filledOption	Null	null
//            correctRate	Integer	50
//            errorRate	Integer	50
//            subjectCommentary	String	梵蒂冈梵蒂冈
//            subjectFrom	Null	null
//            subjectTime	Long	1635750131707
            tomorrowIv.setVisibility(View.INVISIBLE);
            if (data != null) {
                SimpleDateFormat format = new SimpleDateFormat("MM月dd日");
                Date date = new Date(data.getSubjectTime());
                String dateString = format.format(date);
                String dayString = getWeekOfDate(data.getSubjectTime());
                dateTv.setText(dateString + " " + dayString);

                if (position == count - 2) {
                    gotoTodayIv.setVisibility(View.GONE);

                    if (!TextUtils.isEmpty(data.getFilledOption())) {
                        //填写过答案
                        refreshNormalData();

                    } else {
                        //未写过答案
                        answerCl.setVisibility(View.VISIBLE);
                        answerTomorrowCl.setVisibility(View.GONE);
                        answerNormalCl.setVisibility(View.GONE);

                        if (position == 0) {
//                            preDayIv.setVisibility(View.INVISIBLE);
                            preDayIv.setImageResource(R.drawable.icon_pre_day_unable);
                        } else {
                            preDayIv.setImageResource(R.drawable.icon_pre_day);
//                            preDayIv.setVisibility(View.VISIBLE);
                        }

                        titleTv.setText(data.getSubjectTitle());
                        titleTv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                            @Override
                            public void onGlobalLayout() {
                                titleTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                                if (getContext() == null) return;
                                if (titleTv.getLayout() != null && titleTv.getLayout().getLineCount() > titleMaxLines) {
                                    titleTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                                } else {
                                    titleTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 23);

                                }
                            }
                        });

                    }
                } else {
                    //历史展示normal
                    gotoTodayIv.setVisibility(View.VISIBLE);
                    refreshNormalData();


                }
            }
        }


    }

    private void refreshNormalData() {
        answerCl.setVisibility(View.GONE);
        answerTomorrowCl.setVisibility(View.GONE);
        answerNormalCl.setVisibility(View.VISIBLE);
        if (position == 0) {
//            preDayNormal.setVisibility(View.INVISIBLE);
            preDayNormal.setImageResource(R.drawable.icon_pre_day_unable);
        } else {
            preDayNormal.setImageResource(R.drawable.icon_pre_day);
//            preDayNormal.setVisibility(View.VISIBLE);
        }
        String filledOption = data.getFilledOption();
//        if (!TextUtils.isEmpty(filledOption)) {
//            if ("true".equals(filledOption)) {
//                correctTv.setText("已选真的");
//                errorTv.setText("假的");
//            } else {
//                correctTv.setText("真的");
//                errorTv.setText("已选假的");
//            }
//        } else {
//            correctTv.setText("真的");
//            errorTv.setText("假的");
//        }

        titleNormalTv.setText(data.getSubjectTitle());
        titleNormalTv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                titleNormalTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                if (getContext() == null) return;
                if (titleNormalTv.getLayout() != null && titleNormalTv.getLayout().getLineCount() > titleMaxLines) {
                    titleNormalTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
//                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) flagNormalIv.getLayoutParams();
//                    layoutParams.height = ScreenUtils.dip2px(getContext(), 17);
//                    flagNormalIv.setLayoutParams(layoutParams);
                } else {
                    titleNormalTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 23);
//                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) flagNormalIv.getLayoutParams();
//                    layoutParams.height = ScreenUtils.dip2px(getContext(), 23);
//                    flagNormalIv.setLayoutParams(layoutParams);
                }
            }
        });
//        flagNormalIv.setImageResource(data.isAnswerOption() ? R.drawable.icon_answer_true : R.drawable.icon_answer_fake);
        refreshRate(data);
        answerLl.setVisibility(View.VISIBLE);
        if (data.isAnswerOption()) {
            answerFlagIv.setImageResource(R.drawable.ico_fake_answer);
            answerFlagIv.setScaleType(ImageView.ScaleType.FIT_START);

            answerTv.setText("答案：真的");
        } else {
            answerFlagIv.setScaleType(ImageView.ScaleType.FIT_END);
            answerFlagIv.setImageResource(R.drawable.ico_true_answer);

            answerTv.setText("答案：假的");
        }
        if (!TextUtils.isEmpty(filledOption)) {
            yourAnswerTv.setVisibility(View.VISIBLE);
            if ("true".equals(filledOption) && data.isAnswerOption() || !"true".equals(filledOption) && !data.isAnswerOption()) {
                yourAnswerTv.setText("您答对啦");
                yourAnswerTv.setTextColor(getResources().getColor(R.color.text_blue));
            } else {
                yourAnswerTv.setText("您答错啦");
                yourAnswerTv.setTextColor(getResources().getColor(R.color.text_red));
            }
        } else {
            yourAnswerTv.setVisibility(View.GONE);
        }
//        answerInfoTv.setText(String.format(getString(R.string.space_start_2half), data.getSubjectCommentary()));
//        String answerInfo = "解答：" + data.getSubjectCommentary();
//        SpannableString spannableString = new SpannableString(answerInfo);
//        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.text_gray));
//        StyleSpan styleSpan = new StyleSpan(BOLD);
//        spannableString.setSpan(colorSpan,0,2, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
//        spannableString.setSpan(styleSpan,0,2, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
//        answerInfoTv.setText(spannableString);
        answerInfoTv.setText("解答：" + data.getSubjectCommentary());

        answerInfoTv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                answerInfoTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                if (getContext() == null) return;
                int count = answerInfoTv.getLineCount();
                Layout layout = answerInfoTv.getLayout();
                if (layout != null) {
                    if (count > 2) {
                        String textContent = answerInfoTv.getText().toString();
                        StringBuffer threeLinesContent = new StringBuffer();
                        for (int i = 0; i < 2; i++) {
                            threeLinesContent.append(textContent.substring(layout.getLineStart(i), layout.getLineEnd(i)));
                        }

                        if (threeLinesContent.length() < 8){
                            return;
                        }

                        String threeLinesStr = threeLinesContent.substring(0, threeLinesContent.length() - 6) + "...\u3000展开\u3000";
                        SpannableString ss = new SpannableString(threeLinesStr);
                        Drawable drawable = getResources().getDrawable(R.drawable.icon_down_arrow, null);
                        drawable.setBounds(ScreenUtils.dip2px(getContext(), 1), ScreenUtils.dip2px(getContext(), 1), drawable.getMinimumWidth() + ScreenUtils.dip2px(getContext(), 1), drawable.getMinimumHeight() + ScreenUtils.dip2px(getContext(), 1));
                        ImageSpan imageSpan = new ImageSpan(drawable);
                        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.text_blue));
                        ss.setSpan(imageSpan, threeLinesStr.length() - 1, threeLinesStr.length(),
                                Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        ss.setSpan(colorSpan, threeLinesStr.lastIndexOf("展开"), threeLinesStr.lastIndexOf("展开") + 2,
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.text_gray));
                        StyleSpan styleSpan = new StyleSpan(BOLD);
                        ss.setSpan(colorSpan1, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                        ss.setSpan(styleSpan, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                        answerInfoTv.setText(ss);

                    }
                }
            }
        });
    }

    @Override
    public void initData() {

    }

    public void refreshRate(AnswerDetailsListEntity.DataItem answerVO) {
        correctRateTtv.setNoTrapezoid(false);
        correctRateTtv.setBackgroundResource(R.drawable.bg_left_line);
        errorRateTtv.setNoTrapezoid(false);
        errorRateTtv.setBackgroundResource(R.drawable.bg_right_line);
//        correctRateTtv.setText(answerVO.getCorrectRate() + "%");
//        errorRateTtv.setText(answerVO.getErrorRate() + "%");
        correctRateTtv.setText("");
        errorRateTtv.setText("");
        correctRealTv.setText(answerVO.getCorrectRate() + "%人选择");
        errorRealTv.setText(answerVO.getErrorRate() + "%人选择");
        if (answerVO.getErrorRate() == 0) {
            errorRateTtv.setVisibility(View.GONE);
            LinearLayout.LayoutParams correctParams = (LinearLayout.LayoutParams) correctRateTtv.getLayoutParams();
            correctParams.weight = 1;
            correctParams.rightMargin = 0;
            correctRateTtv.setLayoutParams(correctParams);
//            correctRateTtv.setText("100%");
            correctRateTtv.setNoTrapezoid(true);
            correctRateTtv.setBackgroundResource(R.drawable.bg_left_line_corner);
        } else if (answerVO.getCorrectRate() == 0) {
            LinearLayout.LayoutParams errorParams = (LinearLayout.LayoutParams) errorRateTtv.getLayoutParams();
            errorParams.weight = 1;
            errorParams.leftMargin = 0;
            errorRateTtv.setLayoutParams(errorParams);
//            errorRateTtv.setText("100%");
            errorRateTtv.setNoTrapezoid(true);
            errorRateTtv.setBackgroundResource(R.drawable.bg_right_line_corner);
            correctRateTtv.setVisibility(View.GONE);
        } else if (answerVO.getErrorRate() > 0 && answerVO.getErrorRate() < 13) {
            LinearLayout.LayoutParams errorParams = (LinearLayout.LayoutParams) errorRateTtv.getLayoutParams();
            errorParams.weight = 13;
            errorParams.leftMargin = -5;
            errorRateTtv.setLayoutParams(errorParams);
            LinearLayout.LayoutParams correctParams = (LinearLayout.LayoutParams) correctRateTtv.getLayoutParams();
            correctParams.weight = 87;
            correctParams.rightMargin = -5;
            correctRateTtv.setLayoutParams(correctParams);
        } else if (answerVO.getCorrectRate() > 0 && answerVO.getCorrectRate() < 13) {
            LinearLayout.LayoutParams errorParams = (LinearLayout.LayoutParams) errorRateTtv.getLayoutParams();
            errorParams.weight = 87;
            errorParams.leftMargin = -5;
            errorRateTtv.setLayoutParams(errorParams);
            LinearLayout.LayoutParams correctParams = (LinearLayout.LayoutParams) correctRateTtv.getLayoutParams();
            correctParams.weight = 13;
            correctParams.rightMargin = -5;
            correctRateTtv.setLayoutParams(correctParams);
        } else {
            LinearLayout.LayoutParams errorParams = (LinearLayout.LayoutParams) errorRateTtv.getLayoutParams();
            errorParams.weight = answerVO.getErrorRate();
            errorParams.leftMargin = -5;
            errorRateTtv.setLayoutParams(errorParams);
            LinearLayout.LayoutParams correctParams = (LinearLayout.LayoutParams) correctRateTtv.getLayoutParams();
            correctParams.weight = answerVO.getCorrectRate();
            correctParams.rightMargin = -5;
            correctRateTtv.setLayoutParams(correctParams);
        }
    }

    @Override
    public void initEvent() {
        ClickUtils.setFastOnClickListener(answerFl, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.checkAnswerInfo(position);
                }
            }
        });

        ClickUtils.setFastOnClickListener(preDayTomorrowIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.gotoPreDay(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(checkHistoryTomorrowTv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.checkHistory(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(checkHistoryTv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.checkHistory(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(checkHistoryNormalTv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.checkHistory(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(preDayIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (position == 0) {
//                    ToastUtils.showShort("没有更多数据");
                    return;
                }
                if (listener != null) {
                    listener.gotoPreDay(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(nextDayIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.gotoNextDay(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(gotoTodayIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.gotoToday(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(nextDayNormal, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.gotoNextDay(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(chooseLeftIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.chooseLeftAnswer(position);
                }
            }
        });
        ClickUtils.setFastOnClickListener(chooseRightIv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.chooseRightAnswer(position);
                }
            }
        });

        ClickUtils.setFastOnClickListener(preDayNormal, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (position == 0) {
//                    ToastUtils.showShort("没有更多数据");
                    return;
                }
                if (listener != null) {
                    listener.gotoPreDay(position);
                }
            }
        });
    }

    public void setListener(OnAnswerCardListener listener) {
        this.listener = listener;
    }

    public static String getWeekOfDate(long time) {

        Date date = new Date(time);
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekDays[w];
    }


}
